package com.faryangsh.algorithm.basicfor1;

import org.junit.Assert;

import java.util.Iterator;

/**
 * Created by 杨志远 on 2017/8/18
 * email faryangsh@163.com.
 */
public class BagInNode<Item> implements Iterable {
    Node frist;

    @Override
    public Iterator iterator() {
        return new BagIterator();
    }

    private class BagIterator implements Iterator {
        private Node current = frist;

        @Override
        public boolean hasNext() {
            return current!= null;
        }

        @Override
        public Item next() {
            Item currentItem = current.item;
            current = current.next;
            return currentItem;
        }
    }

    private class Node {
        Item item;
        Node next;
    }

    public boolean isEmpty() {
        return frist == null;
    }

    public void add(Item item) {
        Node oldFrist = frist;
        frist=new Node();
        frist.item = item;
        frist.next = oldFrist;
    }

    public Item remove() {
        Assert.assertTrue("bag is empty",!isEmpty());
        Item result = frist.item;
        frist = frist.next;
        return result;
    }


    public static void main(String[] args) {
        BagInNode<String> bag = new BagInNode<>();
        bag.add("one");
        bag.add("two");
        bag.add("three");
        bag.forEach(b->{
            System.out.println(b);
        });
        System.out.println(bag.remove());
        System.out.println(bag.remove());
        System.out.println(bag.remove());

    }
}
